import axios from "axios";
// const urljoin = require("url-join");
import semver from "semver";
import urljoin from "url-join";
export function getNpmInfo(npmName, registry) {
  // console.log(npmName, registry);
  if (!npmName) return;
  const registryUrl = registry || getDefaultRegistry(false);
  const npmInfoUrl = urljoin(registryUrl, npmName);
  return axios
    .get(npmInfoUrl)
    .then((res) => {
      if (res.status === 200) {
        return res.data;
      } else {
        return null;
      }
    })
    .catch((err) => {
      return Promise.reject(err);
    });
  // console.log(npmInfoUrl,'npmInfoUrl');
}
export function getDefaultRegistry(isOrign = false) {
  // https://registry.npmmirror.com/ 淘宝镜像
  //https://registry.npmjs.org/
  return isOrign
    ? "https://registry.npmjs.org"
    : "https://registry.npmmirror.com";
}

export async function getNpmVersion(npmName, registry) {
  const data = await getNpmInfo(npmName, registry);
  if (data) {
    return Object.keys(data.versions);
  } else {
    return [];
  }
}
export function getNpmSemverVersion(baseVersion, versions) {
  versions = versions
    .filter((version) => semver.satisfies(version, `^${baseVersion}`))
    .sort((a, b) => {
      return semver.gt(b, a);
    });  

  return versions;
}
export async function getNpmLastestVersion(baseVersion, npmName, registry) {
  const versions = await getNpmVersion(npmName, registry);
  const newVersions = getNpmSemverVersion(baseVersion, versions);
  if(newVersions&&newVersions.length>0) return newVersions[0];
  
}
export async function getNpmLatestSemverVersion(npmName, registry) {
  let version= await getNpmVersion(npmName, registry);
  if(version){
    version=version.sort((a,b)=> semver.gt(a,b));
    return  version[version.length-1]
  }
  return null
}